IVERILOG ?= iverilog
VVP      ?= vvp
SURFER   ?= surfer
IVERILOG_FLAGS ?= -g2012

SRC_DIR := src
SRC := $(wildcard $(SRC_DIR)/*.sv)

TB ?= tb/strategy_tb.sv
BUILD_DIR := build
TB_BASENAME := $(basename $(notdir $(TB)))

OUT := $(BUILD_DIR)/$(TB_BASENAME).vvp
WAVE := $(BUILD_DIR)/$(TB_BASENAME).vcd


.PHONY: all
all: run

$(OUT): $(SRC) $(TB) | $(BUILD_DIR)
	@echo "[MODE=$(MODE)] compiled $(TB) "
	$(IVERILOG) $(IVERILOG_FLAGS) -I $(SRC_DIR) -o $@ $(SRC) $(TB)

.PHONY: run
run: $(OUT)
	$(VVP) $(OUT)
	mv *.vcd $(BUILD_DIR)/
	$(SURFER) "$(BUILD_DIR)/$(notdir $(WAVE))"

$(BUILD_DIR):
	mkdir $(BUILD_DIR)

UNIT ?=
UNIT_TB := $(if $(UNIT),tb/$(UNIT)_tb.sv,)
.PHONY: unit
unit:
	@if [ -z "$(UNIT)" ]; then \
	  echo "Example usage: make unit UNIT=bbo_track MODE=normal"; exit 1; \
	fi
	@if [ "$(MODE)" = "packed" ]; then \
		echo "ERROR: $(UNIT) does not have a TB for packed arrays"; exit 1; \
	fi  
	@$(MAKE) run TB=$(UNIT_TB) MODE=$(MODE)


.PHONY: help
help:
	@echo "Example Usage:"
	@echo "  make                      			# 用默认的 testbench 运行顶层模块"
	@echo "  make unit UNIT=fv_calc    			# 只进行指定模块的仿真"
	@echo "  make run TB=*_tb.sv  				# 指定 testbench "
	@echo "  make clean                			# 清除 /build 目录"

.PHONY: clean
clean:
	rm -rf $(BUILD_DIR)